package com.thx.user.util;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpSession;

import com.thx.common.spring.BeanFactory;
import com.thx.common.web.WebConstant;
import com.thx.log.LogUtil;
import com.thx.log.model.Log;
import com.thx.log.service.LogManager;
import com.thx.user.listener.UserSessionListener;
import com.thx.user.model.User;
import com.thx.user.view.OnLineUser;

public class OnLineUserUtil {
	/**
	 * 得到在线用户数
	 * @return
	 */
	public static int getOnLineUserCount(){
		synchronized (UserSessionListener.USER_SESSION_MAP) {
			return UserSessionListener.USER_SESSION_MAP.size();
		}
	}
	/**
	 * 得到在线用户的OnLineUser对象集合
	 */
	public static List<OnLineUser> getOnLineUsers(){
		List<OnLineUser> onlineUsers = new ArrayList<OnLineUser>();
		synchronized (UserSessionListener.USER_SESSION_MAP) {
			for(HttpSession sess:UserSessionListener.USER_SESSION_MAP.values()){
				User user = (User) sess.getAttribute(WebConstant.KEY_USER);
				if(user!=null){
					LogManager logMgr = (LogManager) BeanFactory.getBean("logManager");
					Log log =	logMgr.findLastLoginLogByUserId(ModuleConstant.SYSTEM_MANAGER,LogUtil.ACTION_LOGIN,user.getUserId());
					onlineUsers.add(new OnLineUser(user, log));
				}
		    }
		}
		
		return onlineUsers;
	}
	/**
	 * 得到在线用户的用户名字符串,分割
	 */
	public static String getOnLineUsernames(){
		String names="";
		synchronized (UserSessionListener.USER_SESSION_MAP) {
			for(HttpSession sess:UserSessionListener.USER_SESSION_MAP.values()){
				User user = (User) sess.getAttribute(WebConstant.KEY_USER);
				if(user!=null)
					names+= user.getUserName()+",";
		    }
		}
		if(names.length()>0)
			names = names.substring(0, names.length()-1);
		return names;
	}
	/**
	 * 得到在线用户的姓名字符串,分割
	 */
	public static String getOnLineRealnames(){
		String names="";
		synchronized (UserSessionListener.USER_SESSION_MAP) {
			for(HttpSession sess:UserSessionListener.USER_SESSION_MAP.values()){
				User user = (User) sess.getAttribute(WebConstant.KEY_USER);
				if(user!=null)
					names+= user.getRealName()+",";
		    }
		}
		if(names.length()>0)
			names = names.substring(0, names.length()-1);
		return names;
	}
}
